import { EnemyData } from "../class/enemy";
import { GameBalance } from "../data/GameBalance";
import EffectManager from "../manager/effect_manager";
import GameManager from "../manager/game_manager";
import JsonManager from "../manager/json_manager";
import MainManager from "../manager/main_manager";
import ResourceManager from "../manager/resources_manager";
import StorageManager from "../manager/storage_manager";
import UIManager from "../manager/ui_manager";
import { Emitter } from "../utils/emmiter";
import { MessageType } from "../utils/message";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Enemy extends cc.Component {

    globalId: number = 0;
    speed: number = 100;
    exp: number = 3;
    baseHp: number = 10;
    hp: number = 10;
    maxHp: number = 10;
    sprite: cc.Sprite
    isMoving: boolean = true;
    atk: number = 3;
    hasHItBAck: boolean = false

    onLoad() {

        this.isMoving = true;
    }




    getWavehpRate(baseHealth) {
        // let level = StorageManager.instance.levelInfo.curLevel
        // let growthRate = 1.5; // 默认成长率
        // if (level <= 5) {
        //     growthRate = 1.2; // 初期成长较低
        // } else if (level <= 10) {
        //     growthRate = 1.5; // 中期成长
        // } else {
        //     growthRate = 1.8; // 后期成长更高
        // }

        // const additionalScaling = 0.2 * Math.log2(level + 1); // 根据关卡进一步修正
        // return baseHealth * Math.pow(growthRate + additionalScaling, level);
        let level = StorageManager.instance.levelInfo.curLevel;
        let levelAddRAte = 1 * (this.getLevelAddRate(level)) ** (StorageManager.instance.levelInfo.curLevel - 1)
        if (MainManager.instance.curWave >= 10) {
            return 1.5 * levelAddRAte;
        } else if (MainManager.instance.curWave >= 5) {
            return 1 * levelAddRAte;
        }
        return 0.5 * levelAddRAte;
    }


   

    getLevelAddRate(level: number) {
        if (level > 10) {
            return 1.005
        }
        return 1.2
    }

    init(id: number) {
        let info: EnemyData = JsonManager.instance.getDataByName('enemy')[id]
        this.sprite = this.getComponent(cc.Sprite);
        this.speed = info.moveSpeed;
        this.atk = info.atk;
        // cc.log("当前levelrate" + this.getWavehpRate(info.hp))
        // this.maxHp = Math.ceil(info.hp * this.getWavehpRate(info.hp));
      
        const rates = [1.3,  1.005, 1.3, 1.25, 1.4, 1.35, 1.5, 1.45,1.00007,1.15]; // 每个等级段的倍率
        this.maxHp = Math.ceil(GameBalance.calculateHp(StorageManager.instance.levelInfo.curLevel,info.hp, rates ));
        // cc.log('怪物血量',this.maxHp)
        this.hp = this.maxHp;
        this.hasHItBAck = false
        this.sprite.spriteFrame = ResourceManager.instance._Atlas[0].getSpriteFrame(info.sprite)
        if (info.isBoss == 1) {
            this.node.setScale(0.5, 0.5)
        } else {
            this.node.setScale(0.1, 0.1)
        }


    }

    playFlashEffect() {
        if (!this.sprite) {
            console.error("Sprite component not found.");
            return;
        }

        const node = this.sprite.node;

        // 设置闪烁的时间和次数
        const flashDuration = 0.1; // 每次闪烁的持续时间（秒）
        const flashTimes = 2; // 闪烁次数

        // 执行闪烁动画
        let action = cc.repeat(
            cc.sequence(
                cc.fadeTo(flashDuration, 50), // 透明度降低
                cc.fadeTo(flashDuration, 255) // 恢复透明度
            ),
            flashTimes
        );

        // 添加一个回调确保状态恢复
        const resetOpacity = cc.callFunc(() => {
            node.opacity = 255; // 确保最终恢复为完全可见
        });

        // 运行动作
        node.runAction(cc.sequence(action, resetOpacity));
    }



    update(dt) {
        if (!this.isMoving) {
            return;
        }
        // 获取当前节点的位置
        let currentPosition = this.node.position;
        // 修改位置
        this.node.setPosition(currentPosition.x, currentPosition.y - this.speed * dt * cc.director.getScheduler().getTimeScale());
    }



    takeDamage(value: number, isCar: boolean = false) {
        this.hp -= value;
        UIManager.instance.showDamage(this.node, value)
        // EffectManager.instance.createLabel(value,cc.Vec2(this.node.x,this.node.y))
        if (this.hp <= 0) {
            MainManager.instance.removeEnemyById(this.globalId)
        } else {
            if (isCar) {
                this.applyKnockbackWithFade(this.node, 0.5)
            } else {
                this.playFlashEffect()
            }

        }
    }

    applyKnockbackWithFade(target, duration) {
        if (this.hasHItBAck) {
            return
        }
        this.hasHItBAck = true;
        cc.tween(target)
            .parallel(
                cc.tween(target).by(duration, {
                    position: cc.v2(0, 30)
                }),
                cc.tween(target).to(duration / 2, { opacity: 128 }).to(duration / 2, { opacity: 255 })  // 击退过程中节点的透明度渐变
            )
            .start();
    }


    doAttack() {
        if (MainManager.instance.isEndGame) {
            MainManager.instance.removeEnemyById(this.globalId)
            return;
        }
        let node = this.node
        let oriY = node.position.y
        let x = node.x;
        let duration = 1;
        cc.tween(this.node)
            .repeat(99999,

                cc.tween().to(1, { position: cc.v3(x, oriY - 50) }) // 向下移动 50 像素
                    .to(1, { position: cc.v3(x, oriY) })      // 恢复原位置
                    .call(() => {
                        MainManager.instance.player.takeDAmge(this.atk)

                        Emitter.fire(MessageType.uiUpdate);
                        MainManager.instance.damageArea.doFlash()
                        // callback && callback();       // 如果传入了回调，执行回调
                    })
            ).start()


    }



}
